<?php
if(!interface_exists('XController', false)){
	require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'XController.php');
}
class XBasicController extends XObject implements XController{
	private $route = null;
	private $action = null;
	private $view = null;
	private $params = array();
	
	/** 
	 * @return XBasicController
	 */		
	public function setAction($action){
		$this->action = $action;
		return $this;
	}
	
	/** 
	 * @return mixed
	 */	
	public function action($action){
		return $this->action;
	}
	
	/** 
	 * @return XBasicController
	 */		
	public function setView($view){
		$this->view = $view;
		$this->view->setController($this);
		return $this;
	}
	
	/** 
	 * @return mixed
	 */	
	public function view($view){
		return $this->view;
	}
	
	/** 
	 * @return XBasicController
	 */		
	public function setRoute($route){
		$this->route = $route;
		return $this;
	}
	
	/** 
	 * @return XBasicController
	 */		
	public function addParams(array $params){
		foreach($params as $key => $value){
			$this->addParam($key, $value);
		}
		return $this;
	}
	
	/** 
	 * @return XBasicController
	 */		
	public function addParam($key, $value){
		$this->params[$key] = $value;
		return $this;
	}
	
	/** 
	 * @return mixed
	 */		
	public function param($key){
		if(!isset($this->params[$key])){
			return null;
		}
		return $this->params[$key];
	}
	
	/** 
	 * @return array
	 */	
	public function params(){
		return $this->params;
	}	
	
	public function exec(){		
		$action = $this->action;
		if(!method_exists($this, $action)){
			throw new XRouteNotFoundException();
		}
		//handle get/post params
		foreach($_GET as $key => $value){
			$this->addParam(urldecode($key), urldecode($value));
		}
		foreach($_POST as $key => $value){
			$this->addParam(urldecode($key), html_entity_decode($value));
		}
		$this->__before();
		XAnnotationAOPFactory::singleton()->invokeArgs($this, $action);
		if(!$this->view){
			$view = XConfig::singleton()->get('project.controller.'.$this->route.'/'.get_class($this).'.view');
			if(XClassLoader::loader($view)->isSubclassOf('XView')){
				$this->view = new $view();
			}
		}
		if($this->view){
			$this->view->setRoute($this->route);
			$this->view->setName($action);
			$this->view->setAll(get_object_vars($this));
			$this->view->view();
		}
		$this->__after();
	}
	
	/** 
	 * @return XServletRequest
	 */	
	public function request(){
		return XServletRequest::singleton();
	}
	
	/** 
	 * @return XServletResponse
	 */		
	public function response(){
		return XServletResponse::singleton();
	}
	
	public function redirect($url = null){
		return $this->response()->redirect($url);
	}
	
	public function forward($route, array $params = array()){
		if($route == $this->route){
			return true;
		}
		return XRouter::singleton()->forward($route, $params);
	}
	
	protected function __before(){
		
	}
	
	protected function __after(){
		
	}
}
?>